<!--  -->
<template>
  <div class="shopping-car">
    <div class="bg"></div>
    <div class="head">
      购物车
      <span class="option" @click="edit">{{editFlag?'退出编辑':'批量操作'}}</span>
      <div class="text">共{{count}}件宝贝</div>
    </div>
    <div class="order-list">
      <template v-for="(item,index) in shoppingCarList">
        <div class="order-item" :key="index">
          <div class="item-header flex justify-center aligin-center border-bottom-1px">
            <span @click="selectShop(item)" :class="shopCircleStyle(item)"></span>
            <img class="shop-logo" :src="item.shop_logo">
            <span class="title">{{item.shop_name}}</span>
            <!-- <span class="link">进店</span> -->
          </div>
          <template v-for="(_item,_index) in item.list">
            <div :key="_index">
              <div class="item-body">
                <div class="flex aligin-center">
                  <span :class="productCircleStyle(_item)" @click="selectProduct(_item)"></span>
                  <img class="pic" :src="_item.goods_picture" alt="">
                  <div class="info">
                    <div class="product-name ellipsis-line2">{{_item.goods_name}}</div>
                    <div class="tag aligin-center" @click="selectParams(_item)">
                      <span>{{_item.sku_name}}</span>
                      <span class="icon"></span>
                    </div>
                    <!-- <div class="lint">限购5件</div> -->
                  </div>
                </div>
                <div class="price-number flex aligin-center">
                  <span class="price">￥{{_item.price}}</span>
                  <van-stepper :disable-input="true" v-model="_item.num" @change="change($event,_item)" :min="1"/>
                </div>
                <div
                  class="discount flex aligin-center"
                  @click="noticeFlag=true"
                  v-if="parseFloat(_item.reduce)!=0"
                >
                  <span class="discount-money">优惠:{{_item.reduce}}</span>
                  <span>新用户减免</span>
                  <span class="help-icon"></span>
                </div>
              </div>
              <div class="bottom flex aligin-center border-bottom-1px">
                <span class="bottom-tag">参与活动</span>
                <span>{{_item.activity_name}}</span>
              </div>
            </div>
          </template>
        </div>
      </template>
    </div>
    <div class="confirm flex aligin-center border-bottom-1px border-top-1px" v-show="!editFlag">
      <span :class="selectAllStyle" @click="selectAll" v-if="shoppingCarList.length!=0"></span>
      <span @click="selectAll" v-if="shoppingCarList.length!=0">全部</span>
      <span class="total">
        <span>合计</span>
        <span class="total-money">￥{{c_price|toFixed}}</span>
      </span>
      <div class="use-coupon" v-if="c_discount!=0">
        <div>
          已使用优惠券
          <span class="color-red">{{c_discount|toFixed}}元</span>
        </div>
        <div>(未包含运费)</div>
      </div>
      <span class="confirm-btn flex justify-center aligin-center" @click="shoppingCarConfirm">结算</span>
    </div>
    <div
      class="confirm flex aligin-center justify-between border-top-1px border-bottom-1px"
      v-show="editFlag"
    >
      <span :class="selectAllStyle" @click="selectAll"></span>
      <span class="mr-auto" @click="selectAll">全选</span>
      <span class="confirm-btn flex justify-center aligin-center" @click="delFlag=true">删除</span>
    </div>
    <!-- 选择产品参数 -->
    <ProductParams
      ref="productParams"
      :flag.sync="flag"
      v-bind="productDataItem"
      :productOption.sync="productOption"
      :initPic.sync="initPic"
      :c_selectOption.sync="c_selectOption"
      :sku.sync="sku"
      @submit="submit"
      @closeDialog="closeDialog"
      @optionSelected="optionSelected"
    ></ProductParams>
    <!-- 删除对话框 -->
    <div
      class="del-dialog-mask flex justify-center aligin-center"
      v-if="delFlag"
      @click="delFlag=false"
    >
      <div class="del-dialog" @click.stop>
        <div class="title">确定要删除所选商品吗？</div>
        <div class="option flex justify-between">
          <span class="close-btn" @click="delFlag=false">我再想想</span>
          <span class="confirm-btn" @click="delOrder">确认删除</span>
        </div>
      </div>
    </div>
    <!-- 新用户减免说明 -->
    <div
      class="notice-mask flex justify-center aligin-center"
      v-if="noticeFlag"
      @click="noticeFlag=false"
    >
      <div class="notice" @click.stop>
        <div class="title">新用户减免说明</div>
        <div>1. 新用户是指本账号从未在平台生产已支付订单的用户</div>
        <div>2. 首次购买多个商品时,若多个商品都有新用户减免，只计算减免金额最高的商品。</div>
        <div class="confirm-btn" @click="noticeFlag=false">我知道了</div>
      </div>
    </div>
  </div>
</template>

<script>
import ProductParams from "../../components/ProductParams";
import {
  productSku,
  cart,
  cart_destroy,
  cart_store,
  cart_update,
  create_from_cart
} from "../../api/api";
export default {
  components: { ProductParams },
  data() {
    return {
      selectItem: {},
      discount: 0,
      count: 0,
      price: 0,
      editFlag: false, //编辑flag
      delFlag: false, //删除flag
      flag: false, //购物车flag
      noticeFlag: false, //新用户减免说明flag
      c_selectOption: [], //参数规格
      productDataItem: {},
      shoppingCarList: [], //购物车列表
      selectShoppingCarList: [], //选择购物车列表
      productOption: [], //产品参数
      initPic: "", //初始化图片
      sku: [] //匹配规则？
    };
  },
  computed: {
    // 合计价格
    c_price() {
      if (this.selectShoppingCarList.length == 0) {
        return 0;
      } else {
        let array = this.selectShoppingCarList.map(
          item => (parseFloat(item.price) * 100 * item.num) / 100
        );
        let total_money = array.reduce((total, price) => {
          return total + parseFloat(price) * 100;
        }, 0);
        return total_money / 100 - this.c_discount;
      }
    },
    //合计优惠
    c_discount() {
      if (this.selectShoppingCarList.length == 0) {
        return 0;
      } else {
        let array = this.selectShoppingCarList.map(item =>
          parseFloat(item.reduce)
        );
        return Math.max.apply(null, array);
      }
    },
    //全选样式
    selectAllStyle() {
      let list = this.shoppingCarList.map(item => {
        return item.list.map(_item => _item);
      });
      //取出所有产品列表
      let flat_array = list.flat();

      return this.selectShoppingCarList.length == flat_array.length
        ? "circle-selected"
        : "circle";
    }
  },
  watch: {},
  methods: {

    //单件商品价格总计
    itemMoney(price, num) {
      return (parseFloat(price) * 100 * num) / 100;
    },
    //产品数量更改
    change(value, item) {
      if (parseInt(value) == 0) {
        return;
      }
      cart_update({ cart_id: item.cart_id, type: 1, value }).then(
        ({ data: { result } }) => {}
      );
    },
    //编辑
    edit() {
      if (this.shoppingCarList.length == 0) {
        this.$notify("请添加商品到购物车");
        return;
      }
      this.editFlag = !this.editFlag;
    },
    //全选
    selectAll() {
      let list = this.shoppingCarList.map(item => {
        return item.list.map(_item => _item);
      });
      //取出所有产品列表
      let flat_array = list.flat();
      //如果已经全选，设置全部未选中
      if (this.selectShoppingCarList.length == flat_array.length) {
        this.selectShoppingCarList = [];
      } else {
        //如果未全选，设置全选
        this.selectShoppingCarList = [...flat_array];
      }
    },
    //是否包含产品函数
    productInclude(array, item) {
      let index = array.findIndex(product => product.cart_id == item.cart_id);
      return index != -1 ? "circle-selected" : "circle";
    },
    //product circle样式
    productCircleStyle(item) {
      let result = this.productInclude(this.selectShoppingCarList, item);
      return result;
    },
    //是否包含店铺函数
    shopInclude(array, item) {
      let productCount = 0;
      array.forEach(product => {
        item.list.forEach(_item => {
          if (_item.cart_id == product.cart_id) {
            productCount++;
          }
        });
      });
      return productCount == item.list.length ? "circle-selected" : "circle";
    },
    // 店铺circle样式
    shopCircleStyle(item) {
      let result = this.shopInclude(this.selectShoppingCarList, item);
      return result;
    },
    //选择店铺
    selectShop(item) {
      let allInclude = true;
      item.list.forEach(item => {
        let index = this.selectShoppingCarList.findIndex(
          product => product.cart_id == item.cart_id
        );
        if (index == -1) {
          allInclude = false;
        }
      });
      //如果都包含 依次删掉
      if (allInclude) {
        item.list.forEach(item => {
          let index = this.selectShoppingCarList.findIndex(
            product => product.cart_id == item.cart_id
          );
          if (index != -1) {
            this.selectShoppingCarList.splice(index, 1);
          }
        });
      }
      //如果部分包含，依次加满
      else {
        item.list.forEach(item => {
          let index = this.selectShoppingCarList.findIndex(
            product => product.cart_id == item.cart_id
          );
          if (index == -1) {
            this.selectShoppingCarList.push(item);
          }
        });
      }
    },
    //选择产品
    selectProduct(item) {
      let index = this.selectShoppingCarList.findIndex(
        product => item.cart_id == product.cart_id
      );
      if (index != -1) {
        this.selectShoppingCarList.splice(index, 1);
      } else {
        this.selectShoppingCarList.push(item);
      }
    },
    //批量删除
    delOrder() {
      let cart_ids = this.selectShoppingCarList.map(item => item.cart_id);
      let array_string = JSON.stringify(cart_ids);
      cart_destroy({ cart_ids: array_string })
        .then(({ data: { result } }) => {
          this.delFlag = false;
          this.selectShoppingCarList = [];
          return cart();
        })
        .then(({ data: { result } }) => {
          this.shoppingCarList = result.goods;
          this.count = result.count;
          this.discount = parseInt(result.new_sub_price);
          //退出批量编辑
          this.editFlag=false
        });
    },
    //点击重新选择规格
    selectParams(item) {
      this.selectItem = item;
      this.initPic = item.goods_picture;
      let str_format = item.sku_attr_value_items_format;
      let format_array = str_format.split(";");
      let attr_list = format_array.map(item => {
        let item_array = item.split(":");
        return {
          spec_id: parseInt(item_array[0]),
          spec_value_id: parseInt(item_array[1])
        };
      });
      this.c_selectOption = attr_list;
      productSku({ id: item.goods_id }).then(res => {
        this.productOption = res.data.result.spec;
        this.sku = res.data.result.sku;
        this.flag = true;
      });
    },
    // 点击预购
    submit(productNumber, item) {
      cart_update({
        cart_id: this.selectItem.cart_id,
        type: 2,
        value: item.sku_id
      })
        .then(({ data: { result } }) => {
          console.log("result", result);
          this.flag = false;
          return cart();
        })
        .then(({ data: { result } }) => {
          this.shoppingCarList = result.goods;
          this.count = result.count;
          this.discount = parseInt(result.new_sub_price);
          //更新选中的产品列表
          let list = this.shoppingCarList.map(item => {
            return item.list.map(_item => _item);
          });
          //取出所有产品列表
          let flat_array = list.flat();
          // let index = flat_array.findIndex(_item => {
          //   return _item.cart_id == this.selectItem.cart_id;
          // });
          // let select_index=this.selectShoppingCarList.findIndex(_item => {
          //   return _item.cart_id == this.selectItem.cart_id;
          // })
          // if (index != -1&&select_index!=-1) {
          //   this.selectShoppingCarList.splice(select_index, 1, flat_array[index]);
          // }
          let new_array=[]
          flat_array.forEach((item,index)=>{
            this.selectShoppingCarList.forEach((_item,_index)=>{
              if(_item.cart_id==item.cart_id){
                new_array.push(item)
              }
            })
          })
          this.selectShoppingCarList=new_array
        });
    },
    // 关闭产品规格对话框
    closeDialog() {
      this.flag = false;
    },
    //选择规格
    optionSelected(item) {
      //设置单选
      let index = this.c_selectOption.findIndex(_item => {
        return _item.spec_id == item.spec_id;
      });
      if (index != -1) {
        this.c_selectOption.splice(index, 1, item);
      }
    },
    //结算
    shoppingCarConfirm() {
      let submit_list = this.selectShoppingCarList.map(item => item.cart_id);
      create_from_cart({
        device_code: 1,
        cart_ids: JSON.stringify(submit_list)
      }).then(({ data: { result } }) => {
        this.$router.push({name:"orderPay",params:{order_no:result.order_no}})
      });
    }
  },
  created() {},
  mounted() {
    cart().then(({ data: { result } }) => {
      this.shoppingCarList = result.goods;
      this.count = result.count;
      this.discount = parseInt(result.new_sub_price);
      this.price = result.price;
    });
  },
  updated() {}, //生命周期 - 更新之后
  destroyed() {} //生命周期 - 销毁完成
};
</script>
<style lang='less' scoped>
.shopping-car {
  position: relative;
  height: 100%;
  .bg {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 108px;
    background: linear-gradient(
      66deg,
      rgba(232, 48, 56, 1),
      rgba(247, 88, 151, 1)
    );
    z-index: 1;
  }
  .head {
    position: relative;
    padding: 13px 19px 0 17px;
    height: 83px;
    text-align: center;
    font-size: 18px;
    box-sizing: border-box;
    color: #fff;
    z-index: 10;
    .option {
      position: absolute;
      right: 19px;
      top: 17px;
      font-size: 11px;
    }
    .text {
      font-size: 11px;
      margin-top: 28px;
      text-align: left;
    }
  }
  .order-list {
    position: relative;
    height: calc(100% - 126px);
    overflow: auto;
    z-index: 10;
    .order-item {
      margin: 0 15px 23px;
      padding-left: 12px;
      background: #fff;
      box-shadow: 0px 5px 20px 2px rgba(162, 162, 162, 0.19);
      border-radius: 5px;
      .item-header {
        height: 53px;
        .circle {
          margin-right: 14px;
          width: 17px;
          height: 17px;
          border: 1px solid rgba(202, 202, 202, 1);
          border-radius: 50%;
        }
        .circle-selected {
          margin-right: 14px;
          width: 19px;
          height: 19px;
          border-radius: 50%;
          background: url("../../assets/imgs/pay-selected@3x.png");
          background-size: 100% 100%;
        }
        .shop-logo {
          margin-right: 8px;
          width: 20px;
          height: 20px;
          border-radius: 50%;
        }
        .link {
          margin-right: 18px;
          width: 43px;
          height: 21px;
          border: 1px solid rgba(232, 48, 56, 1);
          border-radius: 5px;
          line-height: 21px;
          text-align: center;
          color: rgba(232, 48, 56, 1);
        }
        .title {
          font-size: 12px;
          margin-right: auto;
        }
      }
      .item-body {
        padding: 20px 13px 21px 0;
        .circle {
          flex-shrink: 0;
          margin-right: 14px;
          width: 17px;
          height: 17px;
          border: 1px solid rgba(202, 202, 202, 1);
          border-radius: 50%;
        }
        .circle-selected {
          margin-right: 14px;
          width: 19px;
          height: 19px;
          border-radius: 50%;
          background: url("../../assets/imgs/pay-selected@3x.png");
          background-size: 100% 100%;
        }
        .pic {
          margin-right: 7px;
          flex-shrink: 0;
          width: 103px;
          height: 103px;
          border-radius: 5px;
        }
        .info {
          flex: 1;
          .product-name {
            font-size: 13px;
            line-height: 17px;
            height: 34px;
          }
          .tag {
            padding: 7px;
            margin-top: 11px;
            display: inline-flex;
            font-size: 12px;
            color: rgba(188, 188, 188, 1);
            background: rgba(249, 249, 249, 1);
            border-radius: 3px;
            .icon {
              margin-left: 15px;
              width: 12px;
              height: 6px;
              background: url("../../assets/imgs/arrow-down-gray.png");
              background-size: 100% 100%;
            }
          }
          .lint {
            margin-top: 12px;
            color: #f98c22;
          }
        }
        .discount {
          justify-content: flex-end;
          margin-top: 20px;
          font-size: 12px;
          .discount-money {
            margin-right: 20px;
          }
          .help-icon {
            margin-left: 4px;
            height: 15px;
            width: 15px;
            background: url("../../assets/imgs/new-info.png");
            background-size: 100% 100%;
          }
        }
        .price-number {
          justify-content: flex-end;
          margin-top: 5px;
          font-size: 15px;
          color: rgba(252, 61, 66, 1);
        }
        .price {
          font-size: 15px;
          margin-right: 37px;
        }
      }
      .bottom {
        padding: 10px 10px;
        color: #ea373f;
        font-size: 12px;
        .bottom-tag {
          flex-shrink: 0;
          margin-left: 22px;
          margin-right: 20px;
          color: #fff;
          padding: 4px 5px;
          background: rgba(232, 48, 56, 1);
          border-radius: 3px;
        }
      }
    }
  }
  .confirm {
    position: absolute;
    bottom: 0;
    left: 0;
    padding-left: 16px;
    width: 100%;
    height: 41px;
    font-size: 12px;
    box-sizing: border-box;
    .circle {
      margin-right: 9px;
      width: 17px;
      height: 17px;
      border: 1px solid rgba(202, 202, 202, 1);
      border-radius: 50%;
    }
    .circle-selected {
      margin-right: 9px;
      width: 19px;
      height: 19px;
      border-radius: 50%;
      background: url("../../assets/imgs/pay-selected@3x.png");
      background-size: 100% 100%;
    }
    .total {
      margin-left: 10px;
      flex: 1;
      .total-money {
        font-size: 18px;
        color: #fd2018;
      }
    }
    .use-coupon {
      margin-right: 8px;
      font-size: 10px;
      .color-red {
        color: #fd2018;
      }
    }
    .confirm-btn {
      width: 100px;
      height: 100%;
      font-size: 15px;
      color: #fff;
      background: linear-gradient(
        -90deg,
        rgba(237, 64, 72, 1),
        rgba(251, 104, 113, 1)
      );
    }
  }
  .del-dialog-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 300;
    background: rgba(0, 0, 0, 0.3);
    .del-dialog {
      padding: 44px 27px 21px;
      z-index: 301;
      width: 225px;
      height: 150px;
      box-sizing: border-box;
      border-radius: 5px;
      background: #fff;
      animation: show 0.3s 1;
      box-shadow: 14px 25px 16px 7px rgba(0, 0, 0, 0.05);
      @keyframes show {
        0% {
          opacity: 0;
          transform: scale(1.5);
        }
        100% {
          opacity: 1;
          transform: scale(1);
        }
      }
      .title {
        font-size: 15px;
      }
      .option {
        margin-top: 42px;
        .close-btn {
          width: 76px;
          height: 27px;
          border: 1px solid rgba(252, 64, 111, 1);
          border-radius: 14px;
          font-size: 13px;
          line-height: 27px;
          text-align: center;
          color: #fc406f;
        }
        .confirm-btn {
          width: 76px;
          height: 27px;
          background: rgba(252, 64, 111, 1);
          border-radius: 14px;
          color: #fff;
          font-size: 13px;
          line-height: 27px;
          text-align: center;
        }
      }
    }
  }
  .notice-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 300;
    background: rgba(0, 0, 0, 0.3);
    .notice {
      padding: 44px 27px 21px;
      z-index: 301;
      width: 300px;
      box-sizing: border-box;
      border-radius: 5px;
      background: #fff;
      font-size: 13px;
      line-height: 34px;
      animation: show 0.3s 1;
      box-shadow: 14px 25px 16px 7px rgba(0, 0, 0, 0.05);
      @keyframes show {
        0% {
          opacity: 0;
          transform: scale(1.5);
        }
        100% {
          opacity: 1;
          transform: scale(1);
        }
      }
      .title {
        margin-bottom: 40px;
        font-size: 18px;
        text-align: center;
      }
      .confirm-btn {
        margin: 20px auto 0;
        width: 200px;
        height: 40px;
        font-size: 15px;
        text-align: center;
        line-height: 40px;
        border-radius: 100px;
        color: #fff;
        background: linear-gradient(
          -90deg,
          rgba(237, 64, 72, 1),
          rgba(251, 104, 113, 1)
        );
      }
    }
  }
}
</style>